package com.magima.utils.image;

import java.io.File;
import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ExifInterface;
import android.util.Base64;

public class ImageUtil {
	public static int getImageOrientation(File file) {
		ExifInterface exif;
		int rotate = 0;
		try {
			exif = new ExifInterface(file.getPath());
			int orientation = exif
	                    .getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
			switch ( orientation ) {
			case ExifInterface.ORIENTATION_ROTATE_90:	
				rotate = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				rotate = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				rotate = 270;
				break;
			}
		} catch (IOException e1) {					
			e1.printStackTrace();
		}		
		return rotate;
	}

	public static Bitmap rotateBitmap(Bitmap source, float degree) {
		Matrix matrix = new Matrix();
		matrix.postRotate(degree);
		return Bitmap.createBitmap(source, 0, 0, source.getWidth(),
				source.getHeight(), matrix, true);
	}
	
	public static Bitmap rotateBitmap(File file, float degree){
		Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
		return rotateBitmap( bitmap, degree );
	}
	
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap){
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);    
		Canvas canvas = new Canvas(output);    

		final int color = 0xff424242;    
		final Paint paint = new Paint();    
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());    
		final RectF rectF = new RectF(rect);    
		final float roundPx = 8;    

		paint.setAntiAlias(true);    
		canvas.drawARGB(0, 0, 0, 0);    
		paint.setColor(color);    
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);    

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));    
		canvas.drawBitmap(bitmap, rect, rect, paint);    

		return output;    
	}
	
	public static Bitmap base64ToBitmap(String base64Str){
		byte[] decodedBytes = Base64.decode(base64Str, Base64.DEFAULT);
		return BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
	}
}
